<template>
    <view class="flex align-center border-grey round padding-base">
        <view class="flex align-center" style="width: 160rpx">
            <view class="text-xl icon-erweima"></view>
            <view class="margin-left-sm">验证码</view>
        </view>

        <view style="flex: 1" class="flex align-center justify-between">
            <input style="flex: 1" type="text" placeholder="请输入验证码" @input="handleInput" />
            <view class="flex justify-end" @click="sendCode" style="width: 150rpx">
                <view v-if="countDown === 0" class="text-sm">获取验证码</view>
                <view v-else class="text-sm">{{ countDown }}秒后重发</view>
            </view>
        </view>
    </view>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { sendCodeApi } from "@/api/common";
import { validationMobile } from "@/utils/validation";
import { useTask } from "@/utils/message";

const props = withDefaults(defineProps<{ modelValue: string; mobile: string; type?: string }>(), {
    modelValue: "",
    mobile: "",
    type: ""
});

const countDown = ref<number>(0);
const isSend = ref<boolean>(false);

const emit = defineEmits(["update:modelValue", "change"]);

// 设置验证码
let timeID: number = 0;
const handleCountDown = () => {
    clearInterval(timeID);
    if (countDown.value > 0) {
        timeID = setInterval(() => {
            countDown.value--;
            if (countDown.value === 0) {
              clearInterval(timeID);
              isSend.value = false;
            }
        }, 1000);
    }
};

const sendCode = async () => {
    if (isSend.value) return;

    if (!props.mobile) {
        useTask("请输入手机号");
        return;
    }

    if (!validationMobile(props.mobile)) {
        useTask("请输入正确的手机号");
    }

    await sendCodeApi({
        mobile: props.mobile,
        type: props.type
    });
    countDown.value = 60;
    handleCountDown();
    isSend.value = true;
};

const handleInput = (e: any) => {
    emit("update:modelValue", e.detail.value);
    emit("change", e.detail.value);
};
</script>

<style lang="scss" scoped></style>
